import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:fl_chart/fl_chart.dart';
import 'package:intl/intl.dart';
import '../services/habit_provider.dart';
import '../utils/app_theme.dart';

class AnalyticsScreen extends StatefulWidget {
  const AnalyticsScreen({super.key});

  @override
  State<AnalyticsScreen> createState() => _AnalyticsScreenState();
}

class _AnalyticsScreenState extends State<AnalyticsScreen> with SingleTickerProviderStateMixin {
  late TabController _tabController;
  
  @override
  void initState() {
    super.initState();
    _tabController = TabController(length: 3, vsync: this);
  }
  
  @override
  void dispose() {
    _tabController.dispose();
    super.dispose();
  }
  
  String _getWeekdayName(int day) {
    switch (day) {
      case 1: return '一';
      case 2: return '二';
      case 3: return '三';
      case 4: return '四';
      case 5: return '五';
      case 6: return '六';
      case 7: return '日';
      default: return '';
    }
  }
  
  @override
  Widget build(BuildContext context) {
    final habitProvider = Provider.of<HabitProvider>(context);
    
    return Scaffold(
      appBar: AppBar(
        title: const Text('习惯统计'),
        bottom: TabBar(
          controller: _tabController,
          tabs: const [
            Tab(text: '周统计'),
            Tab(text: '月统计'),
            Tab(text: '习惯详情'),
          ],
        ),
      ),
      body: TabBarView(
        controller: _tabController,
        children: [
          // Weekly stats tab
          _buildWeeklyStatsTab(habitProvider),
          
          // Monthly stats tab
          _buildMonthlyStatsTab(habitProvider),
          
          // Habit details tab
          _buildHabitDetailsTab(habitProvider),
        ],
      ),
    );
  }
  
  Widget _buildWeeklyStatsTab(HabitProvider habitProvider) {
    final weeklyData = habitProvider.getWeeklyCompletionData();
    final now = DateTime.now();
    final weekdayToday = now.weekday;
    
    // Calculate completion rate for the current week
    int totalPossibleCompletions = habitProvider.habits.length * 7;
    int totalCompletions = weeklyData.values.fold(0, (sum, count) => sum + count);
    double completionRate = totalPossibleCompletions > 0 
      ? totalCompletions / totalPossibleCompletions 
      : 0.0;
    
    return SingleChildScrollView(
      padding: const EdgeInsets.all(16),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // Current week summary
          Container(
            padding: const EdgeInsets.all(16),
            decoration: AppTheme.cardDecoration,
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  '本周概览 (${DateFormat('MM/dd').format(now.subtract(Duration(days: weekdayToday - 1)))} - ${DateFormat('MM/dd').format(now.add(Duration(days: 7 - weekdayToday)))})',
                  style: AppTheme.subheadingStyle,
                ),
                const SizedBox(height: 16),
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceAround,
                  children: [
                    _buildStatBox(
                      '完成率',
                      '${(completionRate * 100).toStringAsFixed(1)}%',
                      Icons.pie_chart,
                      AppTheme.primaryColor,
                    ),
                    _buildStatBox(
                      '已完成',
                      '$totalCompletions',
                      Icons.check_circle,
                      AppTheme.successColor,
                    ),
                    _buildStatBox(
                      '连续天数',
                      '${habitProvider.currentStreak}',
                      Icons.local_fire_department,
                      Colors.orange,
                    ),
                  ],
                ),
              ],
            ),
          ),
          const SizedBox(height: 20),
          
          // Weekly chart
          Container(
            padding: const EdgeInsets.all(16),
            decoration: AppTheme.cardDecoration,
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                const Text('每日完成情况', style: AppTheme.subheadingStyle),
                const SizedBox(height: 16),
                SizedBox(
                  height: 200,
                  child: BarChart(
                    BarChartData(
                      alignment: BarChartAlignment.spaceAround,
                      maxY: habitProvider.habits.isEmpty ? 5 : habitProvider.habits.length * 1.2,
                      barTouchData: BarTouchData(
                        enabled: false,
                        touchTooltipData: BarTouchTooltipData(
                          tooltipBgColor: Colors.transparent,
                          tooltipPadding: EdgeInsets.zero,
                          tooltipMargin: 8,
                          getTooltipItem: (group, groupIndex, rod, rodIndex) {
                            return BarTooltipItem(
                              rod.toY.round().toString(),
                              const TextStyle(
                                color: AppTheme.textPrimaryColor,
                                fontWeight: FontWeight.bold,
                              ),
                            );
                          },
                        ),
                      ),
                      titlesData: FlTitlesData(
                        show: true,
                        rightTitles: AxisTitles(
                          sideTitles: SideTitles(showTitles: false),
                        ),
                        topTitles: AxisTitles(
                          sideTitles: SideTitles(showTitles: false),
                        ),
                        bottomTitles: AxisTitles(
                          sideTitles: SideTitles(
                            showTitles: true,
                            getTitlesWidget: (value, meta) {
                              return Text(
                                _getWeekdayName(value.toInt()),
                                style: AppTheme.smallTextStyle,
                              );
                            },
                            reservedSize: 28,
                          ),
                        ),
                        leftTitles: AxisTitles(
                          sideTitles: SideTitles(
                            showTitles: true,
                            getTitlesWidget: (value, meta) {
                              if (value == 0) {
                                return const SizedBox.shrink();
                              }
                              return Text(
                                value.toInt().toString(),
                                style: AppTheme.smallTextStyle,
                              );
                            },
                            reservedSize: 30,
                          ),
                        ),
                      ),
                      borderData: FlBorderData(show: false),
                      barGroups: List.generate(7, (index) {
                        final weekday = index + 1;
                        final count = weeklyData[weekday] ?? 0;
                        
                        return BarChartGroupData(
                          x: weekday,
                          barRods: [
                            BarChartRodData(
                              toY: count.toDouble(),
                              color: weekday == weekdayToday
                                ? AppTheme.accentColor
                                : AppTheme.primaryColor.withOpacity(0.7),
                              width: 16,
                              borderRadius: const BorderRadius.only(
                                topLeft: Radius.circular(4),
                                topRight: Radius.circular(4),
                              ),
                            ),
                          ],
                        );
                      }),
                    ),
                  ),
                ),
              ],
            ),
          ),
          const SizedBox(height: 20),
          
          // Most consistent habits
          Container(
            padding: const EdgeInsets.all(16),
            decoration: AppTheme.cardDecoration,
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                const Text('最佳习惯', style: AppTheme.subheadingStyle),
                const SizedBox(height: 16),
                if (habitProvider.habits.isEmpty)
                  const Text(
                    '尚未添加习惯',
                    style: TextStyle(color: AppTheme.textSecondaryColor),
                  )
                else
                  ...habitProvider.habits
                    .take(3)
                    .map((habit) => ListTile(
                      title: Text(habit.name),
                      subtitle: Text('${habit.getStreakCount()} 天连续完成'),
                      leading: Container(
                        width: 40,
                        height: 40,
                        decoration: BoxDecoration(
                          color: Color(habit.colorValue).withOpacity(0.2),
                          shape: BoxShape.circle,
                        ),
                        child: const Icon(Icons.star),
                      ),
                      trailing: Text(
                        '${(habit.completedDates.length / 30 * 100).toStringAsFixed(0)}%',
                        style: const TextStyle(
                          fontWeight: FontWeight.bold,
                          color: AppTheme.accentColor,
                        ),
                      ),
                    )),
              ],
            ),
          ),
        ],
      ),
    );
  }
  
  Widget _buildMonthlyStatsTab(HabitProvider habitProvider) {
    // Simplified implementation for now
    return SingleChildScrollView(
      padding: const EdgeInsets.all(16),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Container(
            padding: const EdgeInsets.all(16),
            decoration: AppTheme.cardDecoration,
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  '${DateFormat('yyyy年MM月').format(DateTime.now())}概览',
                  style: AppTheme.subheadingStyle,
                ),
                const SizedBox(height: 16),
                const Center(
                  child: Text(
                    '月度统计图表',
                    style: AppTheme.bodyStyle,
                  ),
                ),
                const SizedBox(height: 16),
                const Center(
                  child: Icon(
                    Icons.bar_chart,
                    size: 100,
                    color: AppTheme.primaryColor,
                  ),
                ),
                const SizedBox(height: 16),
                const Center(
                  child: Text(
                    '功能开发中...',
                    style: TextStyle(color: AppTheme.textSecondaryColor),
                  ),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }
  
  Widget _buildHabitDetailsTab(HabitProvider habitProvider) {
    final habits = habitProvider.habits;
    
    return habits.isEmpty
        ? const Center(
            child: Text(
              '尚未添加习惯',
              style: TextStyle(color: AppTheme.textSecondaryColor),
            ),
          )
        : ListView.builder(
            padding: const EdgeInsets.all(16),
            itemCount: habits.length,
            itemBuilder: (context, index) {
              final habit = habits[index];
              final completedCount = habit.completedDates.length;
              final totalDays = DateTime.now().difference(habit.createdAt).inDays + 1;
              final completionRate = totalDays > 0 ? completedCount / totalDays : 0;
              
              return Container(
                margin: const EdgeInsets.only(bottom: 16),
                padding: const EdgeInsets.all(16),
                decoration: AppTheme.cardDecoration,
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Row(
                      children: [
                        Container(
                          width: 40,
                          height: 40,
                          decoration: BoxDecoration(
                            color: Color(habit.colorValue).withOpacity(0.2),
                            shape: BoxShape.circle,
                          ),
                          child: const Icon(Icons.check),
                        ),
                        const SizedBox(width: 12),
                        Expanded(
                          child: Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              Text(
                                habit.name,
                                style: AppTheme.subheadingStyle.copyWith(fontSize: 16),
                              ),
                              Text(
                                '${habit.frequency} · ${habit.amount}',
                                style: AppTheme.smallTextStyle,
                              ),
                            ],
                          ),
                        ),
                        Text(
                          '${(completionRate * 100).toStringAsFixed(0)}%',
                          style: const TextStyle(
                            fontWeight: FontWeight.bold,
                            color: AppTheme.accentColor,
                            fontSize: 18,
                          ),
                        ),
                      ],
                    ),
                    const SizedBox(height: 16),
                    ClipRRect(
                      borderRadius: BorderRadius.circular(8),
                      child: LinearProgressIndicator(
                        value: completionRate.toDouble(),
                        minHeight: 8,
                        backgroundColor: Colors.grey.withOpacity(0.2),
                        valueColor: AlwaysStoppedAnimation<Color>(
                          Color(habit.colorValue),
                        ),
                      ),
                    ),
                    const SizedBox(height: 8),
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        Text(
                          '已完成 $completedCount 天',
                          style: AppTheme.smallTextStyle,
                        ),
                        Text(
                          '总计 $totalDays 天',
                          style: AppTheme.smallTextStyle,
                        ),
                      ],
                    ),
                  ],
                ),
              );
            },
          );
  }
  
  Widget _buildStatBox(String label, String value, IconData icon, Color color) {
    return Container(
      padding: const EdgeInsets.all(12),
      decoration: BoxDecoration(
        color: color.withOpacity(0.1),
        borderRadius: BorderRadius.circular(8),
      ),
      child: Column(
        children: [
          Icon(icon, color: color, size: 28),
          const SizedBox(height: 8),
          Text(
            value,
            style: TextStyle(
              fontSize: 18,
              fontWeight: FontWeight.bold,
              color: color,
            ),
          ),
          Text(
            label,
            style: const TextStyle(
              fontSize: 12,
              color: AppTheme.textSecondaryColor,
            ),
          ),
        ],
      ),
    );
  }
}
